package com.forhappy.light3ds8.arm.bluetooth;

import java.io.IOException;
import java.io.OutputStream;

import com.forhappy.light3ds8.tools.DatasUtils;

import android.bluetooth.BluetoothSocket;
import android.util.Log;

public class ArmMgr {
	public static final int ONCE_SEND_DATAS_NUM = 64; //show one 8*8*8, max datas
	public static final int SENCE_INTERVER = 200; //ervery sence interval, unit ms

	private static Bluetoothclient bluetooth = new Bluetoothclient(null);

	private static final String TAG = "ArmMgr";
	private static SendDataThread sendDatasThread = null;
	public static synchronized void sendDatas(byte[] datas){
		Log.d(TAG, "enter ArmMgr::sendDatas(" + DatasUtils.byteToHexStr(datas) + ")");
		if(sendDatasThread == null ||
			!sendDatasThread.isAlive() ||
			sendDatasThread.isInterrupted()){
			Log.d(TAG, "sendDatasThread is not start, start it");

			sendDatasThread = new SendDataThread();
			sendDatasThread.start();
		} else {
			Log.d(TAG, "sendDatasThread is aready start, thread:" + sendDatasThread.toString());
		}

		sendDatasThread.setDatas(datas);
	}




	static class SendDataThread extends Thread{
		byte[] mSendDatas;

		public SendDataThread() {
			super("sendDatasThread" + System.currentTimeMillis());
		}

		public void setDatas(byte[] datas){
			mSendDatas = datas;
		}
		@Override
		public void run() {
			try {
				while(!isInterrupted()){
					while(!isInterrupted() &&
							bluetooth.getState() != Bluetoothclient.State.Connected){
						sleep(500);
					}
					if(null == mSendDatas || mSendDatas.length == 0) {
						Log.e(TAG, "when send Data, no data is need to send, exit sendDatasThread");
						return;
					}
					final BluetoothSocket socket = bluetooth.getSocket();
					if(null == socket){
						Log.e(TAG, "when send Data, bluetooth is not ready");
						bluetooth.connect();
						sleep(50); //avoid undead loop
						continue;
					} else {
						Log.d(TAG, "have " + mSendDatas.length + " to send! ");
					}

					try{
						OutputStream out = socket.getOutputStream();
						while(!isInterrupted()){
							sendDatas(out, mSendDatas);
						}
					} catch(IOException e){
						//IO exception need to restart bluetootch connect!
						Log.e(TAG, e.toString(), e);
					}
				}
			} catch (InterruptedException e) {
				Log.e(TAG, e.toString(), e);
			}
		}

		private void sendDatas(OutputStream out, byte[] mSendDatas)
				throws IOException, InterruptedException{
			for(int i = 0; i < mSendDatas.length && !interrupted(); i+=ONCE_SEND_DATAS_NUM){
				int sendNum = ONCE_SEND_DATAS_NUM;
				if(i + 64 > mSendDatas.length){
					sendNum = mSendDatas.length - i;
				}
				Log.d(TAG, "send data:" + DatasUtils.byteToHexStr(mSendDatas, i, sendNum));
				out.write(mSendDatas, i, sendNum);
				Thread.sleep(SENCE_INTERVER);
			}
		}

	};


}
